import 'dart:io';

import 'package:ffmpeg_kit_flutter_min/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter_min/ffmpeg_kit_config.dart';
import 'package:ffmpeg_kit_flutter_min/ffprobe_kit.dart';

class FFMPEG {
  FFMPEG._internal() {
    if (!(Platform.isLinux || Platform.isWindows)) {
      FFmpegKitConfig.disableLogs();
    }
  }
  static final FFMPEG _instance = FFMPEG._internal();

  static FFMPEG get inst => _instance;

  /// Automatically appends `-hide_banner -loglevel quiet` for fast execution
  Future<bool> _ffmpegExecute(String command) async {
    if (Platform.isLinux) {
      var process = await Process.run(
          "/usr/bin/ffmpeg", FFmpegKitConfig.parseArguments(command));
      // Process.killPid(process.pid);
      if (process.stderr.isNotEmpty) {
        print("err: ${process.stderr}");
      }
      return process.exitCode == 0;
    }

    final res =
        await FFmpegKit.execute('-hide_banner -loglevel quiet $command');
    // await FFmpegKit.execute(command);
    final out = await res.getOutput();
    final logs = await res.getAllLogs();
    print("ffmpeg out: $out $logs");
    final rc = await res.getReturnCode();
    return rc?.isValueSuccess() ?? false;
  }

  /// Automatically appends `-loglevel quiet -v quiet ` for fast execution
  Future<String?> _ffprobeExecute(String command) async {
    if (Platform.isLinux) {
      var process = await Process.run(
          "/usr/bin/ffmpeg", FFmpegKitConfig.parseArguments(command));
      // Process.killPid(process.pid);
      if (process.stderr.isNotEmpty) {
        return process.stderr;
      }
      return process.stdout;
    }
    final res = await FFprobeKit.execute('-loglevel quiet -v quiet $command');
    return await res.getOutput();
  }

  Future<bool> mergeM3u8({
    required String m3u8Path,
    required String outPath,
  }) async {
    // ffmpeg -y -allowed_extensions ALL -protocol_whitelist "file,http,crypto,tcp,https" -i ts_list.m3u8 -bsf:a aac_adtstoasc  -c copy output.mp4
    return await _ffmpegExecute(
        // '-loglevel quiet -v quiet -y -allowed_extensions ALL -protocol_whitelist "file,http,crypto,tcp,https" -i "$m3u8Path" -bsf:a aac_adtstoasc -c copy "$outPath"');
        ' -loglevel quiet -v quiet -y -f concat -safe 0 -i $m3u8Path -c copy $outPath');
  }
}
